<!--新增小区-->
<template>
	<a-modal v-bind="options">
		<a-form ref="form" :model="community" :rules="communityRules(community)">
			<a-form-item name="name">
				<a-auto-complete v-model:value="community.name" v-bind="searchOptions" :disabled="!community.cityId" style="flex: 1">
					<a-input placeholder="请输入小区名称搜索">
						<template #prefix>
							<search-outlined />
						</template>
					</a-input>
					<template #notFoundContent>
						<a-spin v-if="loadings.search" spinning tip="正在搜索，请稍候……" />
						<a-empty v-else description="暂无匹配数据，请确认地址输入是否正确" />
					</template>
					<template #option="item">
						{{ item.name }}
						<a-divider dashed class="margin-none" />
						<a-typography-text type="secondary">
							<small>{{ item.address }}</small>
						</a-typography-text>
					</template>
				</a-auto-complete>
			</a-form-item>
			<div id="map_container" />
			<a-row :gutter="16">
				<a-col :span="6">
					<a-form-item name="areaId">
						<a-select v-model:value="community.areaId" :options="areas" show-search :field-names="DEFAULT_FIELD_NAME" option-filter-prop="name" placeholder="请选择区域" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item name="townId">
						<a-select v-model:value="community.townId" :options="towns" show-search :field-names="DEFAULT_FIELD_NAME" option-filter-prop="name" placeholder="请选择街道/乡镇" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item name="address">
						<a-input v-model:value="community.address" placeholder="请输入地址" allow-clear />
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
	</a-modal>
</template>

<script lang="ts" setup>
	import {nextTick, reactive, ref, toRef, watchEffect} from 'vue'
	import {Community} from '@/interface/community'
	import {communityRules} from '@/rules/community'
	import {SearchOutlined} from '@ant-design/icons-vue'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import {DEFAULT_FIELD_NAME} from 'yuxin-base/src/constant'
	import houseApi from '@/api/house-api'
	import {message} from 'ant-design-vue'
	import XEUtils from 'xe-utils'

	const props = defineProps<{
		visible: boolean
		value: Community
	}>()

	const loadings = reactive({
		save: false,
		search: false
	})

	const emits = defineEmits(['update:visible', 'close'])
	const options = reactive({
		title: '添加小区',
		width: 1000,
		okText: '保存',
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		class: 'house-community-dialog',
		visible: toRef(props, 'visible'),
		confirmLoading: toRef(loadings, 'save'),
		onCancel() {
			emits('update:visible', false)
			emits('close')
		},
		onOk() {
			form.value.validate().then(() => {
				loadings.save = true

				houseApi
					.addCommunity(community.value)
					.then(({data}) => {
						Object.assign(community.value, data)
						options.onCancel()
						message.success('添加成功')
					})
					.finally(() => (loadings.save = false))
			})
		}
	})

	const form = ref()
	// 小区信息
	const community = toRef(props, 'value')

	// @ts-ignore
	const marker = new AMap.Marker({
		// @ts-ignore
		size: new AMap.Size(30, 42),
		icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png'
	})

	// @ts-ignore
	const geocoder = new AMap.Geocoder({
		// city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
		city: community.value.regionCode
	})

	const getAddress = (position: any[]) => {
		geocoder.getAddress(position, (status: string, result: any) => {
			const {
				info,
				regeocode: {addressComponent, formattedAddress}
			} = result

			if (status === 'complete' && info === 'OK') {
				const {district, township} = addressComponent
				community.value.areaName = district
				community.value.townName = township
				if (formattedAddress) {
					community.value.address = formattedAddress
				}

				const area = areas.value.find((o: any) => o.name === community.value.areaName) || {}
				community.value.areaId = area.id
			}
		})
	}

	let map: any
	// @ts-ignore
	let autocomplete: any = new AMap.Autocomplete({
		datatype: 'poi',
		citylimit: true
	})

	watchEffect(() => {
		if (props.visible) {
			nextTick(() => {
				// @ts-ignore
				map = new AMap.Map('map_container', {
					zoom: 10
				})

				map.setCity(community.value.regionCode)
				autocomplete.setCity(community.value.regionCode)

				if (community.value.name) {
					searchAddress(community.value.name)
				}
			})
		}
	})

	// 地址搜索结果
	const searchOptions = reactive<any>({
		options: [],
		autofocus: true,
		allowClear: true,
		filterOption: false,
		onSearch(keyword: string) {
			if (autocomplete && keyword) {
				searchAddress(keyword)
			}
		},
		onSelect(value: string, option: any) {
			community.value.name = option.name
			community.value.address = option.address
			community.value.lat = option.location.lat
			community.value.lng = option.location.lng

			const pos = [option.location.lng, option.location.lat]

			// 更新地图中心
			map.setZoom(16)
			map.setCenter(pos)

			// 显示标记点
			marker.setMap(map)
			marker.setPosition(pos)

			// 获取区域、街道、详细地址
			getAddress(pos)
		}
	})

	const searchAddress = XEUtils.debounce((keyword: string) => {
		loadings.search = true
		searchOptions.options = []
		community.value.name = keyword
		autocomplete.search(keyword, (status: string, result: any) => {
			loadings.search = false
			const tips = result.tips || []

			for (let tip of tips) {
				tip.value = tip.name
			}

			searchOptions.options = result.tips || []
		})
	}, 300)

	// 区域列表
	const areas = ref<any[]>([])
	watchEffect(async () => {
		if (community.value.cityId) {
			const {data} = await settingApi.getAreaListByCityId(community.value.cityId)
			areas.value = data
			community.value.areaId = null
		}
	})

	// 街道列表
	const towns = ref<any[]>([])
	watchEffect(async () => {
		if (community.value.areaId) {
			const {data} = await settingApi.getTownListByAreaId(community.value.areaId)
			const town = data.find((o: any) => o.name === community.value.townName) || {}

			towns.value = data
			community.value.townId = town.id
		}
	})
</script>

<style lang="less">
	.house-community-dialog {
		.ant-modal-body {
			overflow: auto;
			height: 600px;
			padding-bottom: 0;

			.ant-form {
				height: 100%;
				display: flex;
				flex-direction: column;
			}

			#map_container {
				flex: 1;
				margin-bottom: 24px;
			}

			.amap-icon img {
				width: 100%;
			}
		}
	}
</style>
